package com.weme.mine

import android.app.ActivityOptions
import android.content.Intent
import android.text.TextUtils
import android.util.Log
import androidx.activity.result.contract.ActivityResultContracts
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.jeremyliao.liveeventbus.LiveEventBus
import com.osom.proto.message.Brocast
import com.weme.common.arouter.ARouterHelper
import com.weme.common.arouter.ARouterPaths
import com.weme.common.arouter.LiveRoomBean
import com.weme.common.base.BaseFragment
import com.weme.common.manager.SocketConnectManager.accountLiveData
import com.weme.common.util.AppMkHelper
import com.weme.common.util.LiveConfig
import com.weme.common.util.TimeUtils
import com.weme.common.util.UserMKHelper
import com.weme.common.util.UtilsApp
import com.weme.common.util.downloadImageAsBitmap
import com.weme.common.util.getCountryBean
import com.weme.common.util.gone
import com.weme.common.util.loadImage
import com.weme.common.util.setOnFastClickListener
import com.weme.common.util.setVisible
import com.weme.common.util.showToast
import com.weme.common.util.toFormattedString
import com.weme.common.util.visible
import com.weme.google.GoogleLoginHelper
import com.weme.mine.activity.UserInfoActivity
import com.weme.mine.databinding.FragmentMineBinding
import com.weme.mine.dialog.BindAccountDialog
import com.weme.mine.viewmode.MineViewMode
import dev.kratos.api.user_server.v1.BindRequest
import dev.kratos.api.user_server.v1.GetAccountInfoReply
import dev.kratos.api.user_server.v1.GetFansCountReply
import dev.kratos.api.user_server.v1.GetFollowCountReply
import dev.kratos.api.user_server.v1.GetVipInfoReply
import dev.kratos.api.user_server.v1.Users
import io.agora.chat.BuildConfig
import me.jessyan.autosize.AutoSize
import java.util.IllegalFormatConversionException


@Route(path = ARouterPaths.MINEFRAGMENT)
class MineFragment : BaseFragment<FragmentMineBinding, MineViewMode>() {
    override fun startOperate() {
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR).titleBar(mBinding.calView).init()
        val country = getCountryBean(UserMKHelper.decodeString(UserMKHelper.COUNTRY_CODE))
        country?.let {
            Glide.with(requireActivity()).load(it.countryFlag).into(mBinding.imCountry)
            mBinding.tvCountry.text = it.countryName
        }


        if (UserMKHelper.decodeLong(UserMKHelper.VIP_LEVEL) > 0) {
            viewModel.getVipInfoApi()
            mBinding.groupVip.visible()
        }else{
            mBinding.groupVip.gone()
        }

        //val loginType = AppMkHelper.decodeString(BIND_TYPE)
        //        val parsedArray = Gson().fromJson(loginType, IntArray::class.java)
        //        val users = gson.fromJson(UserMKHelper.decodeString(UserMKHelper.USER_INFO), Users::class.java)
        //        mBinding.calBind.setVisible(parsedArray.isNotEmpty()&&users.uidType == 0 || users.uidType == 3 )
        viewModel.getFollowCountApi()
        viewModel.getFansCountApi()
        accountLiveData.observe(this) {
            mBinding.tvStore.text = it.coins.toFormattedString()
        }
     LiveEventBus.get<Any>(LiveConfig.NET_WORK_MINE).observe(this) {
            if (it is Users) {

                val users = it
                mBinding.calBind.setVisible(it.uidType == 0 || it.uidType == 3)
                mBinding.tvName.text = String.format(it.nickname + "," + it.age)
                UserMKHelper.encode(UserMKHelper.NAME, it.nickname.toString())
                UserMKHelper.encode(UserMKHelper.AGE, it.age.toString())
                mBinding.tvId.text = "ID:"+ it.uid
                if (UserMKHelper.decodeLong(UserMKHelper.VIP_LEVEL) > 0) {
                    viewModel.getVipInfoApi()
                    mBinding.groupVip.visible()
                }else{
                    mBinding.groupVip.gone()
                }
                displayUserAvatar(users.headPic)



            }
            if (it is GetVipInfoReply) {
                try {
                    mBinding.tvExclusive.text = String.format(getString(com.example.resources.R.string.mine_vip_time), "")
                    mBinding.tvExclusiveTime.text = String.format( TimeUtils.timeStamp2DateStr(it.endTime))
                }catch (e: IllegalFormatConversionException){
                    Log.e("error","时间戳有误")
                }

            }
            if (it is GetFollowCountReply) {
                mBinding.tvFollowing.text = it.followCount.toString()
            }
            if (it is GetFansCountReply) {
                mBinding.tvFollowers.text = it.fansCount.toString()
            }
            if (it is GetAccountInfoReply) {
                mBinding.tvStore.setVisible(it.account.coins > 0)
                mBinding.tvStore1.setVisible(it.account.coins > 0)
                mBinding.tvStore.text = it.account.coins.toFormattedString()

            }
        }

        accountLiveData.observe(this){
            mBinding.tvStore.text = it.coins.toFormattedString()
        }
    }



    fun displayUserAvatar(headPic: String) {
        if (!TextUtils.isEmpty(headPic)) {
            val localHeadPic = UserMKHelper.decodeString(AppMkHelper.HEADPIC)
            if (localHeadPic.isNullOrEmpty() || localHeadPic != headPic) {
                // 头像不一致或本地没有头像，下载新的头像
                downloadImageAsBitmap(headPic) { base64String ->
                    if (base64String != null) {
                        // 下载成功，存储并加载新头像
                        UserMKHelper.encode(AppMkHelper.HEADPIC, base64String)
                        mBinding.rimHead.post {
                            mBinding.rimHead.loadImage(base64String)
                        }

                    } else {
                        // 下载失败，显示默认头像
                        mBinding.rimHead.post {
                            mBinding.rimHead.setImageResource(com.example.resources.R.mipmap.avatar_placeholder)
                        }
                    }
                }
            } else {
                // 本地有头像且与服务器头像一致，直接加载本地头像
                mBinding.rimHead.loadImage(localHeadPic)
            }
        } else {
            // 头像 URL 为空，清空本地存储并显示默认头像
            UserMKHelper.encode(AppMkHelper.HEADPIC, "")
            mBinding.rimHead.setImageResource(com.example.resources.R.mipmap.avatar_placeholder)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        accountLiveData.removeObservers(this)
    }

    override fun onResume() {
        super.onResume()
        viewModel.getFollowCountApi()
        viewModel.getFansCountApi() // viewModel.getUserInfo()// 写在main了
    }


    override fun clickListener() {
        mBinding.calCoins.setOnFastClickListener{
            ARouterHelper.navigateToActivity(requireContext(), ARouterPaths.MINE_COINS_ACTIVITY)
        }
        mBinding.calBind.setOnFastClickListener {
            val dialog = BindAccountDialog() {
                val isGooglePlayServicesAvailable: Int = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(requireContext())
                if (isGooglePlayServicesAvailable == ConnectionResult.SUCCESS) {
                    resultLauncher.launch(GoogleLoginHelper.createGoogleIntent(requireContext()))
                } else {
                    UtilsApp.getApp().showToast("Google Play服务不可用，无法进行Google登录等操作")
                }
            }
            dialog.show(requireActivity().supportFragmentManager,"BindAccountDialog")
        }
        mBinding.imSetting.setOnFastClickListener {
//          var dialog =RechargeDialog(object : RechargeDialogCallback{
//              override fun sendGiftInfo(giftInfo: GiftInfo) {
//                  TODO("Not yet implemented")
//              }
//
//          })
//          dialog.show(requireActivity().supportFragmentManager,"")
            val a = Brocast.MatchMessage.newBuilder().setMatchedUser(Brocast.User.newBuilder().setIsVirtual(1).build()).build()
          ARouterHelper.navigateToLiveRoomActivity(requireActivity(), LiveRoomBean(rtcToken ="", userId = 1, chatRoomId = "", channelName = "", channelId = "80000343", matchMessage = a, isIncoming = false))

        //    ARouterHelper.navigateToActivity(requireContext(), ARouterPaths.MINESETTINGSACTIVITY)
        }
        mBinding.rimHead.setOnFastClickListener {

            val intent = Intent(requireContext(), UserInfoActivity::class.java)
            val options = ActivityOptions.makeSceneTransitionAnimation(requireActivity())
            startActivity(intent, options.toBundle()) //   ARouterHelper.navigateToUserInfoActivity(requireContext())
        } //        mBinding.tvEdUserInfo.setOnFastClickListener{
        //            ARouterHelper.navigateToActivity(requireContext(), ARouterPaths.MINE_ED_USERINFO_ACTIVITY)
        //        }
        mBinding.llFollowers.setOnFastClickListener {
            ARouterHelper.navigateToFollwingActivity(requireContext(), 1)
        }
        mBinding.llFollowing.setOnFastClickListener {
            ARouterHelper.navigateToFollwingActivity(requireContext(), 0)
        }
        mBinding.imEd.setOnFastClickListener {
            ARouterHelper.navigateToActivity(requireContext(), ARouterPaths.MINE_ED_USERINFO_ACTIVITY)
        }
    }

    private val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
        it.data?.run {
            setScreenWidthHeight()
            AutoSize.autoConvertDensityOfCustomAdapt(requireActivity(), this@MineFragment)
            GoogleLoginHelper.handleIntent(this, result = { id, token ->
                viewModel.bindAccount(BindRequest.newBuilder().setBindType(2).setGoogleOpenid(id).setGoogleAccessToken(token).build())
            }, block = {
                if(BuildConfig.DEBUG) {
                    showToast("google登录取消")
                }
            })
        }
    }

    override fun getViewModel(): Class<MineViewMode> = MineViewMode::class.java
}